//
//  HDCustomComponent.m
//  HDecoration
//
//  Created by koki on 15-4-24.
//  Copyright (c) 2015年 HDecoration. All rights reserved.
//

#import "HDCustomComponent.h"
#import <objc/runtime.h>
#import <QuartzCore/QuartzCore.h>
#import <Accelerate/Accelerate.h>
#import "UIImage+ImageEffects.h"


@implementation NSObject (PerformBlockAfterDelay)

- (void)performBlock:(void (^)(void))block
          afterDelay:(NSTimeInterval)delay
{
    [self performSelector:@selector(fireBlockAfterDelay:)
               withObject:block
               afterDelay:delay];
}

- (void)fireBlockAfterDelay:(void (^)(void))block {
    block();
}
@end

@implementation UIColor (HexStringToColor)
+(UIColor *)hexStringToColor:(NSString *)stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    
    if ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
    
}

+(UIColor *)skBackgroundColor{
    
    return [self hexStringToColor:@"#f2f2f2"];
}
+(UIColor *)skThemeColor{
    
    return [self hexStringToColor:@"#9E190E"];
}
@end

@implementation UIAlertView (paramAlertView)

-(NSObject*)param
{
    return objc_getAssociatedObject(self,@selector(param));
}

-(void)setParam:(NSObject*)value
{
    objc_setAssociatedObject(self,@selector(param),(id)value,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

@implementation UIView (UIViewFrame)

- (CGFloat)left {
    return self.frame.origin.x;
}

- (void)setLeft:(CGFloat)x {
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

- (CGFloat)top {
    return self.frame.origin.y;
}

- (void)setTop:(CGFloat)y {
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}

- (CGFloat)right {
    return self.frame.origin.x + self.frame.size.width;
}

- (CGFloat)bottom {
    return self.frame.origin.y + self.frame.size.height;
}

- (CGFloat)width {
    return self.frame.size.width;
}

- (void)setWidth:(CGFloat)width {
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

- (CGFloat)height {
    return self.frame.size.height;
}

- (void)setHeight:(CGFloat)height {
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}
- (void)setCenterX:(CGFloat)centerX
{
    CGPoint center = self.center;
    center.x = centerX;
    self.center = center;
}

- (CGFloat)centerX
{
    return self.center.x;
}

- (void)setCenterY:(CGFloat)centerY
{
    CGPoint center = self.center;
    center.y = centerY;
    self.center = center;
}

- (CGFloat)centerY
{
    return self.center.y;
}

@end

@interface DOImageView ()
{
    CGFloat _blurRadius;
    UIColor *_blurTintColor;
    CGFloat _saturationDeltaFactor;
    UIImage *_maskImage;
    UIActivityIndicatorView* actIndicator;
}
@end
@implementation DOImageView
@synthesize imgURLStr;

-(void)dealloc
{
    imgURLStr=nil;
}

-(id)initWithFrame:(CGRect)frame
{
    
    self=[super initWithFrame:frame];
    if (self)
    {
        imgURLStr=nil;
        self.needCache=YES;
        self.defaultImg=@"ic_no_img_detail";
        self.actIndicatorColor=[UIColor blackColor];
        self.image=[UIImage imageNamed:self.defaultImg];
    }
    return self;
}

- (void)setDefaultImg:(NSString *)defaultImg
{
    _defaultImg = defaultImg;
    self.image=[UIImage imageNamed:self.defaultImg];
}

- (void)setEnableBlur:(BOOL)enableBlur
{
    _enableBlur = enableBlur;
    if (enableBlur) {
        _blurRadius = 10;
        _blurTintColor = [UIColor colorWithWhite:0.6 alpha:0.2];
        _saturationDeltaFactor = 1.8;
    }
}

- (void)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)blurTintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage
{
    _blurRadius = blurRadius;
    _blurTintColor = blurTintColor;
    _saturationDeltaFactor = saturationDeltaFactor;
    _maskImage = maskImage;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    for (UIView* view in [self subviews])
    {
        if ([view isMemberOfClass:[UIActivityIndicatorView class]])
        {
            view.frame=self.bounds;
            ((UIActivityIndicatorView*)view).color=self.actIndicatorColor;
            
        }
    }
}
+(BOOL)localExistFile:(NSString*)filename
{
    if([filename length])
    {
        NSArray * array=[filename pathComponents];
        return ([array count]==1);
    }
    return NO;
}

-(void)setImgData:(NSData *)imgData
{
    UIImage *image=[UIImage imageWithData:imgData];
    [self setImage:image];
}

-(void)setImgURLStr:(NSString *)strValue
{
    if ([strValue rangeOfString:@"http://"].location == NSNotFound) {//不包含
        self.image=[UIImage imageNamed:strValue];
        return;
    } else {//包含
        
    }
    NSString *tmpStr = strValue.stringByRemovingPercentEncoding;
    strValue = [tmpStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if(![strValue length])
    {
        imgURLStr=self.defaultImg;
    }
    else
    {
        imgURLStr=[strValue copy];
    }
    
    if (self.needCache&&strValue.length)
    {
        NSData *data = [DOImageView inquiryImageCache:strValue];
        if (data!=nil)
        {
            self.image = [UIImage imageWithData:data];
            if (self.enableBlur)
            {
                self.image = [self.image applyBlurWithRadius:_blurRadius tintColor:_blurTintColor saturationDeltaFactor:_saturationDeltaFactor maskImage:_maskImage];
            }
            if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(doImageViewLoad:img:)])
            {
                [self.delegate doImageViewLoad:self img:self.image];
            }
            return;
        }
    }
    
    if([DOImageView localExistFile:imgURLStr])
    {
        UIImage *image = [UIImage imageNamed:imgURLStr];
        if (image) {
            [self setImage:[UIImage imageNamed:imgURLStr]];
            if (self.enableBlur) {
                self.image = [self.image applyBlurWithRadius:_blurRadius tintColor:_blurTintColor saturationDeltaFactor:_saturationDeltaFactor maskImage:_maskImage];
            }
            if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(doImageViewLoad:img:)])
            {
                [self.delegate doImageViewLoad:self img:self.image];
            }
            return;
        }
    }

    if (!actIndicator) {
        actIndicator=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        CGRect rect=self.bounds;
        actIndicator.frame=rect;
        actIndicator.color=self.actIndicatorColor;
    }
    [actIndicator startAnimating];
    if (!actIndicator.superview) {
        [self addSubview:actIndicator];
    }
    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(  concurrentQueue,^{
        __block NSMutableDictionary *imageDic = [[NSMutableDictionary alloc] initWithCapacity:0];
        __block UIImage *image = nil;
        __block NSString *imageKey = imgURLStr;
        dispatch_sync( concurrentQueue,^{
            NSURL* url=[NSURL URLWithString:imgURLStr];
            NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
            NSHTTPURLResponse *urlResponse = nil;
            NSError *downloadError = nil;
            NSData *imageData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&urlResponse error:&downloadError];
            [imageDic setObject:@"" forKey:imageKey];
            if (downloadError == nil && imageData != nil && urlResponse.statusCode==200)
            {
                image=[UIImage imageWithData:imageData];
                if (image) {
                    [imageDic setObject:image forKey:imageKey];
                    if (self.needCache)
                    {
                        [DOImageView savaImageData:imageData forUrl:strValue];
                    }
                }
            }
        });
        dispatch_sync(dispatch_get_main_queue(),^{
            
            if (![[imageDic allKeys] containsObject:imgURLStr]) {
                return;
            }
            [actIndicator stopAnimating];
            [actIndicator removeFromSuperview];
            
            if (imageDic[imgURLStr]!=nil&&[imageDic[imgURLStr] isKindOfClass:[UIImage class]])
            {
                [self setImage:image];
                if (self.enableBlur)
                {
                    self.image = [self.image applyBlurWithRadius:_blurRadius tintColor:_blurTintColor saturationDeltaFactor:_saturationDeltaFactor maskImage:_maskImage];
                }
            }
            else
            {
                [self setImage:[UIImage imageNamed:self.defaultImg]];
            }
            if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(doImageViewLoad:img:)])
            {
                [self.delegate doImageViewLoad:self img:image];
            }
        });
        
    });
}



+(void)setImgUrl:(NSString *)strValue imgView:(UIImageView*)imgView
{

    NSData *data = [DOImageView inquiryImageCache:strValue];
    if (data!=nil)
    {
        [imgView setImage:[UIImage imageWithData:data]];
        return;
    }

    if([DOImageView localExistFile:strValue])
    {
        [imgView setImage:[UIImage imageNamed:strValue]];
        return;
    }

    UIActivityIndicatorView* actIndicator=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    CGRect rect=imgView.bounds;
    actIndicator.frame=rect;

    actIndicator.color=[UIColor darkGrayColor];
    [actIndicator startAnimating];
    [imgView addSubview:actIndicator];

    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(  concurrentQueue,^{
        __block UIImage *image = nil;
        dispatch_sync( concurrentQueue,^{
            NSURL* url=[NSURL URLWithString:strValue];
            NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
            NSError *downloadError = nil;
            NSData *imageData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&downloadError];
            if (downloadError == nil && imageData != nil)
            {
                image=[UIImage imageWithData:imageData];
                [DOImageView savaImageData:imageData forUrl:strValue];
            }
        });
        dispatch_sync(dispatch_get_main_queue(),^{

            [actIndicator stopAnimating];
            [actIndicator removeFromSuperview];
            if (image != nil)
            {
                 [imgView setImage:image];
            }
        });
    });
}

//查询图片缓存
+ (NSData *)inquiryImageCache:(NSString *)imageUrl
{
    [netEngine.cdlock lock];
    return nil;
}


//存储图片
+(void)savaImageData:(NSData *)imageData forUrl:(NSString *)imageUrl
{
    
}

@end


@interface GXButton ()
{
    UILabel *_unreadLabel;
}
@end
@implementation GXButton
@synthesize object,numberCount;

-(void)setNumberCount:(int)count
{
    numberCount=count;
    [self layoutSubviews];
}

-(void)playCountAnimation
{
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.3;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.3, 1.3, 1.3)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [_unreadLabel.layer addAnimation:animation forKey:nil];
}

- (void) layoutSubviews
{
    
    [super layoutSubviews];
    if (_unreadLabel==nil&& self.enableTip)
    {
        _unreadLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.width-11)/2.0,9, 16, 16)];
        _unreadLabel.backgroundColor = [UIColor redColor];
        _unreadLabel.textColor = [UIColor whiteColor];
        _unreadLabel.textAlignment = NSTextAlignmentCenter;
        _unreadLabel.font = [UIFont boldSystemFontOfSize:11];
        _unreadLabel.layer.cornerRadius = 8;
        _unreadLabel.clipsToBounds = YES;
        _unreadLabel.hidden=YES;
        [self addSubview:_unreadLabel];
    }
    
    if(self.relayout)
    {
        self.imageView.frame =self.imageViewFrame;
        self.titleLabel.frame=self.titleLabelFrame;
    }
    
    if ( self.enableTip)
    {
        _unreadLabel.hidden=!self.numberCount;
        [self bringSubviewToFront:_unreadLabel];
        _unreadLabel.text = [NSString stringWithFormat:@"%d",self.numberCount];
    }
    
    if (_unreadLabel==nil&&self.showTip) {
        CGFloat left = self.width-8;
        CGFloat top = 5;
        if (self.imageViewFrame.size.width) {
            left = self.imageViewFrame.origin.x+self.imageViewFrame.size.width-2;
            top = self.imageViewFrame.origin.y-5>top?self.imageViewFrame.origin.y-5:top;
        }
        _unreadLabel = [[UILabel alloc] initWithFrame:CGRectMake(left, top, 8, 8)];
        _unreadLabel.backgroundColor = KRedColor;
        _unreadLabel.layer.cornerRadius = _unreadLabel.width/2.0;
        _unreadLabel.layer.borderColor = [UIColor whiteColor].CGColor;
        _unreadLabel.layer.borderWidth = 1.5f;
        _unreadLabel.clipsToBounds = YES;
        _unreadLabel.hidden = YES;
        [self addSubview:_unreadLabel];
    }
    
    if (self.showTip) {
        _unreadLabel.hidden=!self.numberCount;
        [self bringSubviewToFront:_unreadLabel];
    }
}
-(void)dealloc
{
    object=nil;
}
@end


@implementation HyperlinksButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

-(void)setColor:(UIColor *)color{
    lineColor = [color copy];
    [self setNeedsDisplay];
}

- (void) drawRect:(CGRect)rect {
    CGRect textRect = self.titleLabel.frame;
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    
    CGFloat descender = self.titleLabel.font.descender;
    if([lineColor isKindOfClass:[UIColor class]]){
        CGContextSetStrokeColorWithColor(contextRef, lineColor.CGColor);
    }
    
    //起点坐标
    CGContextMoveToPoint(contextRef, textRect.origin.x+3, textRect.origin.y + textRect.size.height + descender+3);
    //终点坐标
    CGContextAddLineToPoint(contextRef, textRect.origin.x + textRect.size.width-4, textRect.origin.y + textRect.size.height + descender+3);
    
    CGContextClosePath(contextRef);
    CGContextDrawPath(contextRef, kCGPathStroke);
}
@end

@implementation MSBtnWithDynamicImg

- (void)setImageViewFrame:(CGRect)imageViewFrame
{
    [super setImageViewFrame:imageViewFrame];
    self.dynamicImgView.frame = imageViewFrame;;
}

- (void)setImgUrl:(NSString *)imgUrl
{
    _imgUrl = imgUrl;
    if (!_dynamicImgView.superview) {
        [self addSubview:self.dynamicImgView];
    }
    self.dynamicImgView.imgURLStr = imgUrl;
}

- (void)setDefaultImgUrl:(NSString *)defaultImgUrl
{
    _defaultImgUrl = defaultImgUrl;
    if (!_dynamicImgView.superview) {
        [self addSubview:self.dynamicImgView];
    }
    self.dynamicImgView.defaultImg = defaultImgUrl;
}

- (void)doImageViewLoad:(DOImageView*)imgView img:(UIImage*)img
{
    [self.dynamicImgView removeFromSuperview];
    if (img) {
        [self setImage:img forState:UIControlStateNormal];
    } else {
        if (self.defaultImgUrl.length) {
            [self setImage:[UIImage imageNamed:self.defaultImgUrl] forState:UIControlStateNormal];
        }
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    if(self.relayout)
    {
        self.imageView.frame =self.imageViewFrame;
        self.titleLabel.frame=self.titleLabelFrame;
    }
}

- (DOImageView *)dynamicImgView
{
    if (!_dynamicImgView) {
        _dynamicImgView = [[DOImageView alloc] initWithFrame:self.bounds];
        _dynamicImgView.delegate = (id)self;
        _dynamicImgView.layer.masksToBounds = YES;
        _dynamicImgView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _dynamicImgView;
}

@end

@implementation GXScrollToolBar
@synthesize dataArray,delegate,curSeletedBtn;

-(void)dealloc
{
    self.curSeletedBtn=nil;
    self.dataArray=nil;
    items=nil;
    _scrollContainer=nil;
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        items=[[NSMutableArray alloc]initWithCapacity:0];
        _scrollContainer=[[UIScrollView alloc]initWithFrame:self.bounds];
        _scrollContainer.bounces=NO;
        _scrollContainer.showsHorizontalScrollIndicator=NO;
        _scrollContainer.showsVerticalScrollIndicator=NO;
        _scrollContainer.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _scrollContainer.delegate=(id)self;
        _scrollContainer.backgroundColor=[UIColor clearColor];
        curSeletedBtn=nil;
        
        self.backgroundColor=[UIColor clearColor];
        self.bgImageView=[[DOImageView alloc] initWithFrame:self.bounds];
        [self insertSubview:self.bgImageView atIndex:0];
        [self addSubview:_scrollContainer];
    }
    return self;
}

-(GXButton*)getBtnIndex:(int)index
{
    return [items objectAtIndex:index];
}

-(void)TransferResponse:(GXButton*)sender;
{
    if(curSeletedBtn!=nil)
    {
        if(curSeletedBtn==sender && curSeletedBtn.selected)
        {
            [self.delegate scrollToolBarBtnRepeat];
            return;
        }
        curSeletedBtn.selected=NO;
    }
    self.curSeletedBtn=sender;
    curSeletedBtn.selected=YES;
    [self.delegate scrollToolBarBtnAction:sender toolBar:self];
    
}

-(void)setDefaultSelectedIndex:(int)index
{
    GXButton* sender=[items objectAtIndex:index];
    [self TransferResponse:sender];
}

-(void)initItems
{
    CGSize size=_scrollContainer.frame.size;
    int xpos=0;
    int count=(int)[dataArray count];
    
    //添加功能按钮
    for (int i=0;i< count; i++)
    {
    }
    [_scrollContainer setContentSize:CGSizeMake(xpos,size.height)];
}


-(void)setDataArray:(NSArray*)array
{
    dataArray=[array copy];
    [self initItems];
}

@end

@interface SXProgressHUD ()
@property(nonatomic,assign)NSInteger hudCount;
@end
@implementation SXProgressHUD
-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    for (UIView* item in [self subviews])
    {
        if ([item isMemberOfClass:[UIActivityIndicatorView class]])
        {
            item.center=self.center;
        }
    }
}

+(void) showHUDAddedTo:(UIView*)view animated:(BOOL)animated
{
    for (UIView* item in [view subviews])
    {
        if ([item isMemberOfClass:[SXProgressHUD class]])
        {
            ((SXProgressHUD *)item).hudCount++;
            return;
        }
    }
    SXProgressHUD* hud=[[SXProgressHUD alloc]initWithFrame:view.bounds];
    hud.backgroundColor=[UIColor clearColor];
    [view addSubview:hud];
    
    UIActivityIndicatorView* actIndicator=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    actIndicator.frame=hud.bounds;
    UIColor* color=(view.backgroundColor==[UIColor blackColor])?[UIColor whiteColor]:[UIColor blackColor];
    actIndicator.color=color;
    [hud addSubview:actIndicator];
    [actIndicator startAnimating];
}

-(void)dealloc
{
    for (UIView* item in [self subviews])
    {
        [item removeFromSuperview];
    }
}

+(void) hideAllHUDsForView:(UIView*)view animated:(BOOL)animated
{
    for (UIView* item in [view subviews])
    {
        if ([item isMemberOfClass:[SXProgressHUD class]])
        {
            if (!((SXProgressHUD *)item).hudCount)
            {
                [item removeFromSuperview];
            }
            else
            {
                ((SXProgressHUD *)item).hudCount--;
            }
        }
    }
}

@end


@interface SXTextView ()
@property(nonatomic,strong)UILabel *placeholderLabel;
@end

@implementation SXTextView
@synthesize placeholder;


-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor=[UIColor clearColor];
        self.placeholderLabel=[[UILabel alloc]init];
        self.placeholderLabel.frame=self.placeholderLabel.frame=CGRectMake(5, 8, self.width-10, 20);
        self.placeholderLabel.numberOfLines=0;
        self.placeholderLabel.font=[UIFont fontWithName:@"STHeitiSC-Light" size:14];
        self.placeholderLabel.autoresizingMask=UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        self.placeholderLabel.backgroundColor=[UIColor clearColor];
        [self insertSubview:self.placeholderLabel atIndex:0];
        self.placeholderLabel.textColor = UIColorFromRGB(0xd0d0d4);
        self.font=[UIFont fontWithName:@"STHeitiSC-Light" size:14];
        self.scrollEnabled=YES;
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidBeginEditingNotification object:self];
    }
    return self;
}

- (void)setFont:(UIFont *)font
{
    [super setFont:font];
    self.placeholderLabel.font=font;
    CGSize size = [HDUtil sizeWithString:placeholder font:self.font size:CGSizeMake(self.placeholderLabel.width, CGFLOAT_MAX)];
    self.placeholderLabel.height = size.height;
    if (self.placeholderLabel.height>20) {
        self.placeholderLabel.top = 5;
    }
}

-(void)dealloc
{
    self.placeholderLabel=nil;
    self.placeholder=nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(void)textDidChange
{
    self.placeholderLabel.hidden=(self.text.length!=0);
    self.placeholderLabel.frame=CGRectMake(5, 8, self.width-10, 20);
    CGSize size = [HDUtil sizeWithString:placeholder font:self.font size:CGSizeMake(self.placeholderLabel.width, CGFLOAT_MAX)];
    self.placeholderLabel.height = size.height;
    if (self.placeholderLabel.height>20) {
        self.placeholderLabel.top = 5;
    }
}

-(void)setPlaceholder:(NSString *)strValue
{
    placeholder=[strValue copy];
    self.placeholderLabel.text=placeholder;
    CGSize size = [HDUtil sizeWithString:placeholder font:self.font size:CGSizeMake(self.placeholderLabel.width, CGFLOAT_MAX)];
    self.placeholderLabel.height = size.height;
    if (self.placeholderLabel.height>20) {
        self.placeholderLabel.top = 5;
    }
}

@end


@implementation SXNavigation
static SXNavigation* navgation;

-(void)dealloc
{
    rootViewCtr=nil;
    viewStack=nil;
}

+(SXNavigation*)shareNavigation
{
    @synchronized(self)
    {
        if(navgation==nil)
        {
            navgation=[[SXNavigation alloc]init];
        }
    }
    return navgation;
}

-(BOOL)isToRootViewController
{
    return (index==0);
}

+(id)allocWithZone:(struct _NSZone *)zone
{
    @synchronized(self)
    {
        if (navgation==nil )
        {
            navgation=[super allocWithZone:zone];
            return navgation;
        }
    }
    return nil;
}

-(void)initWithRootViewController:(UIViewController*)_viewCtr
{
    viewStack=nil;
    viewStack=[[NSMutableArray alloc]initWithCapacity:0];
    rootViewCtr=nil;
    rootViewCtr=_viewCtr;
    index=0;
    [viewStack insertObject:rootViewCtr atIndex:index];
}

- (void)pushViewController:(UIViewController*)_viewCtr animated:(BOOL)animated
{
    UIViewController* disappearVctr=[viewStack objectAtIndex:index];
    [disappearVctr viewWillDisappear:animated];
    
    index++;
    [viewStack insertObject:_viewCtr atIndex:index];
    
    CGRect rect=_viewCtr.view.frame;
    CGPoint point= CGPointMake(rect.origin.x+rect.size.width, rect.origin.y);
    rect.origin=point;
    _viewCtr.view.frame=rect;
    [rootViewCtr.view addSubview:_viewCtr.view];
    
    if (animated)
    {
        CGContextRef context=UIGraphicsGetCurrentContext();
        [UIView beginAnimations:nil context:context];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:0.3];
        point= CGPointMake(0, rect.origin.y);
        rect.origin=point;
        _viewCtr.view.frame=rect;
        [UIView commitAnimations];
    }
    else
    {
        point= CGPointMake(0, rect.origin.y);
        rect.origin=point;
        _viewCtr.view.frame=rect;
    }
    [_viewCtr viewWillAppear:animated];
}

-(void)removeTopView:(UIViewController*)_viewCtr
{
    [_viewCtr.view removeFromSuperview];
}

-(void)clearData
{
    viewStack=nil;
    index=0;
}

- (void)popToRootViewControllerAnimated:(BOOL)animated
{
    if(index==0)
        return;
    
    UIViewController* _viewCtr=[viewStack objectAtIndex:index];
    [_viewCtr viewWillDisappear:animated];
    
    CGRect rect=_viewCtr.view.frame;
    CGPoint point= CGPointMake(rect.origin.x+rect.size.width, rect.origin.y);
    rect.origin=point;
    
    CATransition* animation=[CATransition animation];
    [animation setType:kCATransitionPush];
    [animation setSubtype:kCATransitionFromLeft];
    [animation setDuration:0.3f];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    _viewCtr.view.frame=rect;
    [_viewCtr.view.layer addAnimation:animation forKey:nil];
    [viewStack removeObjectAtIndex:index];
    
    for (index-=1;index>0;index--)
    {
        UIViewController* Vctr=[viewStack objectAtIndex:index];
        [Vctr.view removeFromSuperview];
        [viewStack removeObjectAtIndex:index];
    }
    
    [self performBlock:
     ^{
         [_viewCtr.view removeFromSuperview];
     } afterDelay:0.5f];
    
    UIViewController* appearVctr=[viewStack objectAtIndex:0];
    [appearVctr viewWillAppear:animated];
}

- (void)popViewControllerAnimated:(BOOL)animated
{
    if(index==0)
        return;
    
    UIViewController* _viewCtr=[viewStack objectAtIndex:index];
    
    CGRect rect=_viewCtr.view.frame;
    CGPoint point= CGPointMake(rect.origin.x+rect.size.width, rect.origin.y);
    rect.origin=point;
    
    if (animated)
    {
        CATransition* animation=[CATransition animation];
        [animation setType:kCATransitionPush];
        [animation setSubtype:kCATransitionFromLeft];
        [animation setDuration:0.3f];
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
        _viewCtr.view.frame=rect;
        [_viewCtr.view.layer addAnimation:animation forKey:nil];
    }
    else
    {
        _viewCtr.view.frame=rect;
    }
    [_viewCtr viewWillDisappear:animated];
    
    [self performSelector:@selector(removeTopView:) withObject:_viewCtr afterDelay:0.5f];
    [viewStack removeObjectAtIndex:index];
    index--;
    UIViewController* appearVctr=[viewStack objectAtIndex:index];
    [appearVctr viewWillAppear:animated];
    
}
@end


@implementation GXLevelControl
@synthesize levelNum,levelTotal;
-(void)setLevelNum:(int)num
{
    levelNum=num;
    
    if (self.selectedImgUrl==nil)
    {
        self.selectedImgUrl=@"btn_star_pre";
    }
    for (int i=0; i<levelNum; i++)
    {
        UIImageView* imgView=[items objectAtIndex:i];
        [imgView setImage:[UIImage imageNamed: self.selectedImgUrl]];
    }
}

-(void)setLevelTotal:(int)num
{
    levelTotal=num;
    CGRect rect=self.bounds;
    float x=0;
    items=[[NSMutableArray alloc]initWithCapacity:0];
    
    if (self.normalImgUrl==nil)
    {
        self.normalImgUrl=@"btn_star_nor";
    }
    
    for (int i=0; i<levelTotal; i++)
    {
        CGRect rc=CGRectMake(x, 0, (rect.size.width-2.0)/levelTotal, rect.size.height);
        UIImageView* imgView=[[UIImageView alloc]initWithFrame: rc];
        [imgView setImage:[UIImage imageNamed:self.normalImgUrl]];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        
        [ self addSubview:imgView];
        [items insertObject:imgView atIndex:i];
        
        x+=(rect.size.width/levelTotal+0.5);
    }
    
}
@end





@implementation DOMarkView
@synthesize selected;

-(id)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if (self)
    {
        self.showLine=YES;
        [self initUI];
    }
    return self;
}

-(void)initUI
{
    int x=15,y=10;
    CGRect rect=CGRectMake(x, y,self.width-2*x, 20);
    UILabel* titleLabel=[[UILabel alloc] initWithFrame:rect];
    titleLabel.tag=101;
    titleLabel.font=[UIFont fontWithName:@"STHeitiSC-Light" size:14];
    [self addSubview:titleLabel];
}

-(void)setTitle:(NSString *)title
{
    _title=title;
    UILabel* titleLabel=(UILabel*)[self viewWithTag:101];
    [titleLabel setText:title];
}

-(void)setSelected:(NSString *)value
{
    selected=value;
    if (value!=nil)
    {
        NSArray* selectedItems=[value componentsSeparatedByString:@"/"];
        for (NSString* item in selectedItems)
        {
            for (int i=0; i<self.marks.count; i++)
            {
                UIButton* btn=(UIButton*)[self viewWithTag:(200+i)];
                if ([btn.titleLabel.text isEqualToString:item])
                {
                    btn.selected=YES;
                    if (self.isSingle)
                    {
                        self.curBtn=btn;
                    }
                    btn.layer.borderColor=KRedColor.CGColor;
                    btn.backgroundColor=KRedColor;
                }
            }
            
        }
    }
    else
    {
        [self cleanSelected];
    }
}

-(void)setMarks:(NSArray *)marks
{
    _marks=marks;
    for (int i=0; i<marks.count; i++)
    {
        NSString* strText=marks[i];
        UIFont* font=[UIFont fontWithName:@"STHeitiSC-Light" size:13];
        float width=[HDUtil sizeWithString:strText font:font size:CGSizeMake(MAXFLOAT, 28)].width;
        width+=20;
        CGRect rect=CGRectMake(0, 0, width, 28);
        UIButton* btn=[[UIButton alloc] initWithFrame:rect];
        btn.tag=200+i;
        btn.layer.cornerRadius=3;
        btn.layer.borderWidth=0.5;
        btn.layer.borderColor=[UIColor lightGrayColor].CGColor;
        btn.titleLabel.font=font;
        [btn setTitle:strText forState:UIControlStateNormal];
        [btn setTitle:strText forState:UIControlStateSelected];
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
    }
    
    if(self.showLine)
    {
        DOImageView* sepLine=[[DOImageView alloc]initWithFrame:CGRectMake(15,0, self.width-30, 0.5)];
        sepLine.imgURLStr=@"dot";
        sepLine.tag=102;
        [self addSubview:sepLine];
    }
    [self resetlayout];
}

-(void)resetlayout
{
    float offsetX=15,offsetY=35;
    float widthMax=self.width-15;
    for (int i=0; i<self.marks.count; i++)
    {
        UIView* btn=[self viewWithTag:200+i];
        if ((offsetX+btn.width)>widthMax)
        {
            offsetX=15;
            offsetY+=(btn.height+10);
        }
        btn.left=offsetX;
        btn.top=offsetY;
        offsetX+=(btn.width+10);
    }
    
    self.height=(offsetY+38);
    UIView* line=[self viewWithTag:102];
    if (line!=nil)
    {
        line.top=self.height-0.5;
    }
    
}

-(void)cleanSelected
{
    for (int i=0; i<self.marks.count; i++)
    {
        UIButton* btn=(UIButton*)[self viewWithTag:(200+i)];
        btn.selected=NO;
        btn.backgroundColor=[UIColor whiteColor];
        btn.layer.borderColor=[UIColor lightGrayColor].CGColor;
    }
    self.curBtn=nil;
    selected=nil;
}

-(void)btnAction:(UIButton*)sender
{
    [HDUtil hidenKeyBoard];
    if (self.isSingle)
    {
        if (self.curBtn!=sender)
        {
            self.curBtn.selected=NO;
            self.curBtn.layer.borderColor=[UIColor lightGrayColor].CGColor;
            self.curBtn.backgroundColor=[UIColor whiteColor];
            self.curBtn=sender;
        }
    }
    
    sender.selected=!sender.selected;
    if (sender.selected)
    {
        sender.backgroundColor=KRedColor;
        sender.layer.borderColor=KRedColor.CGColor;
    }
    else
    {
        sender.layer.borderColor=[UIColor lightGrayColor].CGColor;
        sender.backgroundColor=[UIColor whiteColor];
    }
}

-(NSString*)selected
{
    NSString* str=nil;
    
    for (int i=0; i<self.marks.count; i++)
    {
        UIButton* btn=(UIButton*)[self viewWithTag:(200+i)];
        if (btn.selected)
        {
            if (str==nil)
            {
                str=[NSString string];
            }
            else
            {
                str=[str stringByAppendingString:@"/"];
            }
            
            str=[str stringByAppendingString:btn.titleLabel.text];
        }
    }
    return str;
}
@end


@implementation MSTagCollectionView

- (id)initWithFrame:(CGRect)frame
{
    MSTagCollectionLayout *layout=[[MSTagCollectionLayout alloc] init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    layout.minimumInteritemSpacing = 0.3;
    layout.minimumLineSpacing = 0.3;
    self = [super initWithFrame:frame collectionViewLayout:layout];
    if (self) {
        [self registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"tagCell"];
        self.delegate = (id)self;
        self.dataSource = (id)self;
        self.bounces = NO;
        self.scrollEnabled = NO;
        self.layer.cornerRadius = 5;
        self.layer.borderWidth = 0.8;
        self.layer.borderColor = [UIColor lightGrayColor].CGColor;
        self.backgroundColor = [UIColor lightGrayColor];
    }
    return self;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row>=self.tagArray.count) {
        return;
    }
    if ([self.tagDelegate respondsToSelector:@selector(collectionView:didSelectItemAtIndexPath:)]) {
        [self.tagDelegate collectionView:collectionView didSelectItemAtIndexPath:indexPath];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.tagArray.count%self.columnCount) {
        return self.tagArray.count+(self.columnCount-self.tagArray.count%self.columnCount);
    } else {
        return self.tagArray.count;
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"tagCell";
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    UILabel *tagLabel = [[UILabel alloc] initWithFrame:cell.bounds];
    if (indexPath.row<self.tagArray.count) {
        tagLabel.text = self.tagArray[indexPath.row];
    } else {
        tagLabel.text = @"";
    }
    tagLabel.textAlignment = NSTextAlignmentCenter;
    tagLabel.font = [UIFont fontWithName:@"STHeitiSC-Light" size:14];
    tagLabel.adjustsFontSizeToFitWidth = YES;
    tagLabel.textColor = kLightGrayColor;
    cell.backgroundColor = [UIColor whiteColor];
    [cell.contentView addSubview:tagLabel];
    
    if ((indexPath.row+1)%self.columnCount==0) {    //每行最后一个cell宽度与collectionview右边缘对齐
        cell.width = self.width-cell.left;
    }
    if (!tagLabel.text.length) {
        cell.width = cell.width+1;
        UIView *coverView = [[UIView alloc] initWithFrame:CGRectMake(cell.left+self.left, cell.top, cell.width+1, cell.height+1)];
        coverView.backgroundColor = [UIColor whiteColor];
        [self.superview addSubview:coverView];
    }
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((self.width-(self.columnCount-1))/self.columnCount, 40);
}

- (void)setTagArray:(NSArray *)tagArray
{
    _tagArray = [tagArray copy];
    [self reloadData];
}

@end


@implementation MSTagCollectionLayout

-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray* attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
    //从第二个循环到最后一个
    for(int i = 1; i < [attributes count]; ++i) {
        //当前attributes
        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
        //上一个attributes
        UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
        //我们想设置的最大间距，可根据需要改
        NSInteger maximumSpacing = 1;
        //前一个cell的最右边
        NSInteger originX = CGRectGetMaxX(prevLayoutAttributes.frame);
        //前一个cell的最上边
        NSInteger originY = CGRectGetMinY(prevLayoutAttributes.frame);
        //如果当前一个cell的最右边加上我们想要的间距加上当前cell的宽度依然在contentSize中，我们改变当前cell的原点位置
        //不加这个判断的后果是，UICollectionView只显示一行，原因是下面所有cell的x值都被加到第一行最后一个元素的后面了
        if(originX + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = originX + maximumSpacing;
            frame.origin.y = originY;
            currentLayoutAttributes.frame = frame;
        } else {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.y = originY + maximumSpacing + frame.size.height;
            currentLayoutAttributes.frame = frame;
        }
    }
    return attributes;
}

@end

@implementation MSFavorBtn
- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    [self layoutBtn];
}

- (void)layoutBtn
{
    self.imageViewFrame = CGRectMake(self.width/2.0-10, self.height/2.0-9.5, 20, 19);
    self.relayout = YES;
    self.layer.cornerRadius = self.width/2.0;
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
    [self setImage:[UIImage imageNamed:@"zan_normal"] forState:UIControlStateNormal];
    [self setImage:[UIImage imageNamed:@"zan_selected"] forState:UIControlStateSelected];
    [self addTarget:self action:@selector(favorBtnAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)favorBtnAction:(GXButton *)sender
{
    if ([self.delegate respondsToSelector:@selector(favorBtnAction:)])
    {
                    [self.delegate favorBtnAction:sender];
    }
    [self flip];

}

-(void)flip
{
    CGContextRef context=UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.4];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self cache:YES];
    self.selected=!self.selected;
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}

@end

@interface MSTagView ()
@end
@implementation MSTagView

-(id)initWithFrame:(CGRect)frame font:(UIFont *)font
{
    self = [super initWithFrame:frame];
    if (self) {
        self.font = font;
    }
    return self;
}

- (void)setTagArray:(NSArray *)tagArray
{
    _tagArray = tagArray;
    for (int i=0; i<tagArray.count; i++) {
        UILabel *tagLabel = (UILabel *)[self viewWithTag:100+i];
        CGSize size = [HDUtil getSizeWithText:tagArray[i] font:self.font];
        if (!tagLabel) {
            tagLabel = [[UILabel alloc] init];
            tagLabel.layer.cornerRadius = self.height/2.0;
            tagLabel.layer.masksToBounds = YES;
            
            if (self.tagBgColor) {
                tagLabel.backgroundColor = self.tagBgColor;
            }else {
                tagLabel.backgroundColor = kYellowColor;
            }
            if (self.tagBorderColor) {
                tagLabel.layer.borderColor = self.tagBorderColor.CGColor;
                tagLabel.layer.borderWidth = 0.5;
            }
            if (self.textColor) {
                tagLabel.textColor = self.textColor;
            }else {
                tagLabel.textColor = [UIColor whiteColor];
            }
            tagLabel.font = self.font;
            tagLabel.textAlignment = NSTextAlignmentCenter;
            tagLabel.tag = 100+i;
        }
        if (!tagLabel.superview) {
            [self addSubview:tagLabel];
        }
        tagLabel.frame = CGRectMake(0, 0, size.width+15, self.height);
        tagLabel.text = tagArray[i];
    }
    for (UILabel *label in self.subviews) {
        if (label.tag>100+tagArray.count) {
            [label removeFromSuperview];
        }
    }
    [self layoutTagLabels];
}

- (void)layoutTagLabels
{
    UILabel *formerLabel = (UILabel *)[self viewWithTag:100];
    formerLabel.left = 0;
    for (int i=1; i<self.tagArray.count; i++) {
        UILabel *label = (UILabel *)[self viewWithTag:100+i];
        if (formerLabel.right+5+label.width<self.width) {
            label.left = formerLabel.right + 5;
            label.top = formerLabel.top;
        } else {
            label.left = 0;
            label.top = formerLabel.bottom+5;
        }
        formerLabel = label;
        self.height = formerLabel.bottom;
    }
}

- (void)setTagBgColor:(UIColor *)tagBgColor
{
    _tagBgColor = tagBgColor;
    for (int i=1; i<self.tagArray.count; i++) {
        UILabel *tagLabel = (UILabel *)[self viewWithTag:100+i];
        tagLabel.backgroundColor = tagBgColor;
    }
}

- (void)setTextColor:(UIColor *)textColor
{
    _textColor = textColor;
    for (int i=1; i<self.tagArray.count; i++) {
        UILabel *tagLabel = (UILabel *)[self viewWithTag:100+i];
        tagLabel.textColor = textColor;
    }
}

- (void)setTagBorderColor:(UIColor *)tagBorderColor
{
    _tagBorderColor = tagBorderColor;
    for (int i=1; i<self.tagArray.count; i++) {
        UILabel *tagLabel = (UILabel *)[self viewWithTag:100+i];
        tagLabel.layer.borderColor = tagBorderColor.CGColor;
        tagLabel.layer.borderWidth = 0.5;
    }
}

+(CGFloat)tagViewHeight:(NSArray *)tagArray font:(UIFont *)font frame:(CGRect)frame
{
    if (!tagArray.count) {
        return 0;
    }
    CGFloat height = frame.size.height;
    CGFloat width;
    CGSize size = [HDUtil getSizeWithText:tagArray[0] font:font];
    width = size.width+15;
    for (int i=1; i<tagArray.count; i++) {
        CGSize size = [HDUtil getSizeWithText:tagArray[i] font:font];
        if (width+size.width+15+5<frame.size.width) {
            width+=size.width+15+5;
        } else {
            height+=frame.size.height;
            size = [HDUtil getSizeWithText:tagArray[i] font:font];
            width = size.width;
        }
    }
    return height;
}

@end

const static CGFloat homeListBtnHeight = 80.0;
@interface MSHomeBtnListView ()
@property(nonatomic,strong)UIScrollView *containerView;
@end
@implementation MSHomeBtnListView

- (void)setDataArray:(NSArray *)dataArray
{
    _dataArray = [dataArray copy];
    [self.containerView removeFromSuperview];
    self.containerView = [[UIScrollView alloc] initWithFrame:self.bounds];
    self.containerView.scrollsToTop = NO;
    [self addSubview:self.containerView];
    for (int i=0; i<_dataArray.count; i++) {
        MSBtnWithDynamicImg *btn = [MSBtnWithDynamicImg buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(APPFRAME.size.width/4.0*(i%4), i/4*homeListBtnHeight, APPFRAME.size.width/4.0, homeListBtnHeight);
        btn.imageViewFrame = CGRectMake((APPFRAME.size.width/4.0-45)/2.0, (homeListBtnHeight-70)/2.0, 45, 45);
        btn.dynamicImgView.layer.cornerRadius = btn.imageViewFrame.size.width/2.0;
        btn.titleLabelFrame = CGRectMake(0, (homeListBtnHeight-70)/2.0+55, btn.width, 15);
        btn.imageView.layer.cornerRadius = btn.imageViewFrame.size.width/2.0;
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        btn.titleLabel.font = [UIFont fontWithName:@"STHeitiSC-Light" size:12];
        [btn setTitleColor:kDarkGrayColor forState:UIControlStateNormal];
        btn.relayout = YES;
        btn.tag = 100+i;
//        MSImageInfo *imageInfo = _dataArray[i];
//        [btn setTitle:imageInfo.imageTitle forState:UIControlStateNormal];
//        [btn setImage:[UIImage imageNamed:@"ic_no_img_detail"] forState:UIControlStateNormal];
//        btn.imgUrl = imageInfo.imageUrl;
        [btn addTarget:self action:@selector(selectBtnWithIndex:) forControlEvents:UIControlEventTouchUpInside];
        [self.containerView addSubview:btn];
    }
//    self.containerView.contentSize = CGSizeMake(APPFRAME.size.width/4.0*titleArray.count, self.height);
    self.height = homeListBtnHeight*(dataArray.count%4==0?dataArray.count/4:dataArray.count/4+1);
}

- (void)selectBtnWithIndex:(MSBtnWithDynamicImg *)sender
{
    if ([self.delegate respondsToSelector:@selector(clickBtnListView:onIndex:)]) {
        [self.delegate clickBtnListView:self onIndex:sender.tag-100];
    }
}

@end

@interface MSSwitch ()
@property(nonatomic,strong)UIImageView *trackImageView;
@property(nonatomic,strong)UIButton *thumbBtn;
@end
@implementation MSSwitch
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initUI];
        self.trackImageView.frame = CGRectMake(0, (frame.size.height-5)/2.0, frame.size.width, 5);
        self.thumbBtn.frame = CGRectMake(0, frame.size.height/2.0-7.5, 15, 15);
    }
    return self;
}

- (void)initUI
{
    self.clipsToBounds = YES;
    self.trackImageView = [[UIImageView alloc] init];
    self.thumbBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [self.thumbBtn addGestureRecognizer:panGesture];
    [self addSubview:self.trackImageView];
    [self addSubview:self.thumbBtn];
    self.trackOnImage = [[UIImage imageNamed:@"switch_track_on"] stretchableImageWithLeftCapWidth:3 topCapHeight:2.5];
    self.trackOffImage = [[UIImage imageNamed:@"switch_track_off"] stretchableImageWithLeftCapWidth:5 topCapHeight:2.5];
    self.thumbOnImage = [UIImage imageNamed:@"switch_thumb_on"];
    self.thumbOffImage = [UIImage imageNamed:@"switch_thumb_off"];
    [self.thumbBtn addTarget:self action:@selector(clickAction) forControlEvents:UIControlEventTouchUpInside];
    [self addTarget:self action:@selector(clickAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    self.trackImageView.frame = CGRectMake(0, (frame.size.height-5)/2.0, frame.size.width, 5);
    self.thumbBtn.frame = CGRectMake(0, frame.size.height/2.0-7.5, 15, 15);
}

- (void)setTrackOnImage:(UIImage *)trackOnImage
{
    _trackOnImage = trackOnImage;
}

- (void)setTrackOffImage:(UIImage *)trackOffImage
{
    _trackOffImage = trackOffImage;
    self.trackImageView.image = trackOffImage;
}

- (void)setThumbOnImage:(UIImage *)thumbOnImage
{
    _thumbOnImage = thumbOnImage;
    [self.thumbBtn setImage:thumbOnImage forState:UIControlStateSelected];
}

- (void)setThumbOffImage:(UIImage *)thumbOffImage
{
    _thumbOffImage = thumbOffImage;
    [self.thumbBtn setImage:thumbOffImage forState:UIControlStateNormal];
    [self.thumbBtn setImage:thumbOffImage forState:UIControlStateHighlighted];
}

- (void)setThumbLeft:(CGFloat)thumbLeft
{
    if (thumbLeft<0||thumbLeft>self.width-self.thumbBtn.width) {
        return;
    }
    self.thumbBtn.left = thumbLeft;
}

- (void)setOn:(BOOL)on
{
    _on = on;
    self.trackImageView.image = on?self.trackOnImage:self.trackOffImage;
    self.thumbBtn.selected = on;
    CGFloat moveWidth = on?(self.width-self.thumbBtn.width-self.thumbBtn.left):self.thumbBtn.left;
    CGFloat animationDuration = moveWidth/(self.width-self.thumbBtn.width)*0.2;
    [UIView animateWithDuration:animationDuration animations:^{
        self.thumbBtn.left = self.on?self.width-self.thumbBtn.width:0;
    }];
    [self sendActionsForControlEvents:UIControlEventValueChanged];
}

#pragma mark - actions
- (void)handlePan:(UIPanGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan || gesture.state == UIGestureRecognizerStateChanged) {
        CGPoint translation = [gesture translationInView:self];
        [self setThumbLeft:self.thumbBtn.left+translation.x];
        [gesture setTranslation:CGPointZero inView:self];
        [self sendActionsForControlEvents:UIControlEventValueChanged];
    }
    else if (gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateCancelled) {
        self.on = self.thumbBtn.left>(self.width-self.thumbBtn.width)/2.0;
    }
}

- (void)clickAction
{
    self.on = !self.on;
}

@end

@interface MSPageControl ()
- (void)updateDots;
@end

@implementation MSPageControl
@synthesize imagePageStateHighlighted,imagePageStateNormal;


- (void)setImagePageStateNormal:(UIImage *)image
{
    imagePageStateNormal = image;
    [self updateDots];
}

- (void)setImagePageStateHighlighted:(UIImage *)image
{
    imagePageStateHighlighted = image;
    [self updateDots];
}

- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    [super endTrackingWithTouch:touch withEvent:event];
    [self updateDots];
}

-(void)updateDots
{
    if (imagePageStateNormal || imagePageStateHighlighted)
    {
        NSArray *subview = self.subviews;
        for (NSInteger i = 0; i < [subview count]; i++)
        {
            UIView *dot = [subview objectAtIndex:i];
            dot.width=2;
            dot.height=2;
            if (self.currentPage == i)
            {
                dot.backgroundColor=[UIColor colorWithPatternImage:imagePageStateHighlighted];
            }
            else
            {
                dot.backgroundColor=[UIColor colorWithPatternImage:imagePageStateNormal];
            }
        }
    }
    
}

- (void)setCurrentPage:(NSInteger)page {
    [super setCurrentPage:page];
    [self updateDots];
}


@end



static char UIScrollViewTwitterCover;

@implementation UIScrollView (TwitterCover)

- (void)setTwitterCoverView:(CHTwitterCoverView *)twitterCoverView
{
    [self willChangeValueForKey:@"twitterCoverView"];
    objc_setAssociatedObject(self, &UIScrollViewTwitterCover,
                             twitterCoverView,
                             OBJC_ASSOCIATION_ASSIGN);
    [self didChangeValueForKey:@"twitterCoverView"];
}

- (CHTwitterCoverView *)twitterCoverView
{
    return objc_getAssociatedObject(self, &UIScrollViewTwitterCover);
}

- (void)addTwitterCoverWithImage:(UIImage*)image
{
    [self addTwitterCoverWithImage:image withTopView:nil];
}

- (void)addTwitterCoverWithImage:(UIImage*)image withTopView:(UIView*)topView
{
    CHTwitterCoverView *view = [[CHTwitterCoverView alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, CHTwitterCoverViewHeight) andContentTopView:topView];
    
    view.backgroundColor = [UIColor clearColor];
    view.image = image;
    view.scrollView = self;
    [self addSubview:view];
    if (topView) {
        [self addSubview:topView];
    }
    self.twitterCoverView = view;
}

- (void)removeTwitterCoverView
{
    [self.twitterCoverView removeFromSuperview];
    self.twitterCoverView = nil;
}

@end


@implementation CHTwitterCoverView
{
    NSMutableArray *blurImages_;
    UIView *topView;
}

- (id)initWithFrame:(CGRect)frame
{
    return [self initWithFrame:frame andContentTopView:nil];
}

- (id)initWithFrame:(CGRect)frame andContentTopView:(UIView*)view
{
    self = [super initWithFrame:frame];
    if (self) {
        self.contentMode = UIViewContentModeScaleAspectFill;
        self.clipsToBounds = YES;
        blurImages_ = [[NSMutableArray alloc] initWithCapacity:20];
        topView = view;
        self.scrollView.scrollsToTop = NO;
    }
    return self;
}

- (void)setImage:(UIImage *)image
{
    [super setImage:image];
    [blurImages_ removeAllObjects];
    [self prepareForBlurImages];
}

- (void)prepareForBlurImages
{
    CGFloat factor = 0.24;
    [blurImages_ addObject:self.image];
    for (NSUInteger i = 0; i < 9; i++) {//值越大，越模糊
        [blurImages_ addObject:[self.image boxblurImageWithBlur:factor]];
        factor-=0.03;
    }
}

- (void)setScrollView:(UIScrollView *)scrollView
{
    [_scrollView removeObserver:self forKeyPath:@"contentOffset"];
    _scrollView = scrollView;
    [_scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)removeFromSuperview
{
    [_scrollView removeObserver:self forKeyPath:@"contentOffset"];
    [topView removeFromSuperview];
    [super removeFromSuperview];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    if (self.scrollView.contentOffset.y < 0) {
        
        CGFloat offset = -self.scrollView.contentOffset.y;
        topView.frame = CGRectMake(0, -offset, SCREEN_WIDTH, topView.bounds.size.height);
        
        self.frame = CGRectMake(-offset,-offset + topView.bounds.size.height, SCREEN_WIDTH+ offset * 2, CHTwitterCoverViewHeight + offset);
        NSInteger index = offset / 10;
        //        NSLog(@"索引值：%ld",index);
        if (index < 0) {
            index = 1;
        }
        else if(index == 0) {//第一张
            index = 1;
        }
        else if(index >= blurImages_.count) {//最后一张
            index = blurImages_.count - 1;
            
        }
        UIImage *image = blurImages_[index];
        if (self.image != image) {
            [super setImage:image];
        }
        if (offset >80) {
            self.scrollView.contentOffset = CGPointMake(0, -80);
        }
        
    }
    else {
        topView.frame = CGRectMake(0, 0, SCREEN_WIDTH, topView.bounds.size.height);
        
        self.frame = CGRectMake(0,topView.bounds.size.height, SCREEN_WIDTH, CHTwitterCoverViewHeight);
        UIImage *image = blurImages_[1];
        
        if (self.image != image) {
            [super setImage:image];
        }
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    [self setNeedsLayout];
}

@end

@implementation UIImage (Blur)

-(UIImage *)boxblurImageWithBlur:(CGFloat)blur {
    //    NSLog(@"每次增加===：%F",blur);
    NSData *imageData = UIImageJPEGRepresentation(self, 1); // convert to jpeg
    UIImage* destImage = [UIImage imageWithData:imageData];
    
    
    if (blur < 0.f || blur > 1.f) {
        blur = 0.5f;
    }
    int boxSize = (int)(blur * 40);
    boxSize = boxSize - (boxSize % 2) + 1;
    
    CGImageRef img = destImage.CGImage;
    
    vImage_Buffer inBuffer, outBuffer;
    
    vImage_Error error;
    
    void *pixelBuffer;
    
    
    //create vImage_Buffer with data from CGImageRef
    
    CGDataProviderRef inProvider = CGImageGetDataProvider(img);
    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
    
    
    inBuffer.width = CGImageGetWidth(img);
    inBuffer.height = CGImageGetHeight(img);
    inBuffer.rowBytes = CGImageGetBytesPerRow(img);
    
    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
    
    //create vImage_Buffer for output
    
    pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
    
    if(pixelBuffer == NULL)
        NSLog(@"No pixelbuffer");
    
    outBuffer.data = pixelBuffer;
    outBuffer.width = CGImageGetWidth(img);
    outBuffer.height = CGImageGetHeight(img);
    outBuffer.rowBytes = CGImageGetBytesPerRow(img);
    
    // Create a third buffer for intermediate processing
    void *pixelBuffer2 = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
    vImage_Buffer outBuffer2;
    outBuffer2.data = pixelBuffer2;
    outBuffer2.width = CGImageGetWidth(img);
    outBuffer2.height = CGImageGetHeight(img);
    outBuffer2.rowBytes = CGImageGetBytesPerRow(img);
    
    //perform convolution
    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer2, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    if (error) {
        NSLog(@"error from convolution %ld", error);
    }
    error = vImageBoxConvolve_ARGB8888(&outBuffer2, &inBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    if (error) {
        NSLog(@"error from convolution %ld", error);
    }
    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    if (error) {
        NSLog(@"error from convolution %ld", error);
    }
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(outBuffer.data,
                                             outBuffer.width,
                                             outBuffer.height,
                                             8,
                                             outBuffer.rowBytes,
                                             colorSpace,
                                             (CGBitmapInfo)kCGImageAlphaNoneSkipLast);
    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    
    //clean up
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);
    
    free(pixelBuffer);
    free(pixelBuffer2);
    CFRelease(inBitmapData);
    
    CGImageRelease(imageRef);
    
    return returnImage;
}

@end

@implementation NSTimer (MSBlock)

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval
                                         block:(void(^)())block
                                       repeats:(BOOL)repeats
{
    return [self scheduledTimerWithTimeInterval:interval
                                         target:self
                                       selector:@selector(blockInvoke:)
                                       userInfo:[block copy]
                                        repeats:repeats];
}

+ (void)blockInvoke:(NSTimer *)timer {
    void (^block)() = timer.userInfo;
    if(block) {
        block();
    }
}

@end















